/*
 * DataAcquisition.c
 *
 *  Created on: 2021年11月19日
 *      Author: CameronLee
 */

#include "DataAcquisition.h"

extern osMutexId_t DataAcquireMutexHandle;
extern osMessageQueueId_t MeaTempHandle;
volatile uint16_t ADC_ConvertedValue = 0;

volatile float Deta_Enr_BOX ;

extern osEventFlagsId_t SysStatusFlagHandle;
extern osMutexId_t Control_MutexHandle;

uint8_t BeginToAcquireADCValue(void)
{
	uint8_t res;

	res = HAL_ADC_Start_DMA(&hadc1,(uint32_t*)&ADC_ConvertedValue,1);
	if (res == HAL_OK) {
		return 0;
	} else {
		return res;
	}
}


uint8_t StopAcquiringADCValue(void)
{
	uint8_t res;
	res = HAL_ADC_Stop_DMA(&hadc1);
	if (res == HAL_OK) {
			return 0;
		} else {
			return res;
		}
}




uint8_t DataAcquireTask(void)
{
	float temp1,temp2;
	//uint8_t res = 1;
	GX18B20_Begin(Env_GX18B20);
	GX18B20_Begin(Box_GX18B20);

	//res = osMutexAcquire(Control_MutexHandle,100);
	osDelay(500);

	temp1 =  GX18B20_Get_Temp(Env_GX18B20);
	temp2 =  GX18B20_Get_Temp(Box_GX18B20);

	//if(res){
		osMessageQueuePut(MeaTempHandle,&temp2,osPriorityNormal3,500);
	//}else{
		//加热任务已经被挂起
		//清掉队列中的值
	//	if(osMessageQueueGetMsgSize (MeaTempHandle)){
			osMessageQueueReset(MeaTempHandle);
	//	}
	//}

	if(READ_BIT(osEventFlagsGet(SysStatusFlagHandle),0x10000)){
		Data_Packet_Send(temp1,temp2,Target_Temperature,ADC_ConvertedValue);
		osEventFlagsClear (SysStatusFlagHandle,0x10000);
	}
	//调用打包发送函数   是否 给定 一个发送时机的标准？ 比如系统稳定之后开启发送？


	UI_Environment_Temperature = temp1;
	UI_BOX_Temperature = temp2;
	UI_Measurement_Data = (float)ADC_ConvertedValue/4096*3.3f;

	//释放信号量 让显示任务更新屏幕！
	//osMutexRelease(DataAcquireMutexHandle);

	Deta_Enr_BOX =temp1 - temp2;
	//osMutexRelease(Control_MutexHandle);


	return 0;
}


static void SYS_Current_Data_Send(Data_Packet_TypeDef* data , uint16_t len)
{
	CDC_Transmit_FS((uint8_t*)data,len);
	osEventFlagsSet(SysStatusFlagHandle,0x10);

	HAL_UART_Transmit(&huart1,(uint8_t*)data,len, 100);
	osEventFlagsSet(SysStatusFlagHandle,0x20);

}

uint8_t Data_Packet_Send(float enr_temr,float box_temp,
						float target,uint16_t ADC_Value)
{
	Data_Packet_TypeDef data;
	data.Data_First = 0xAA;
	data.Data_Kind = 0xA0;
	data.Data_Length = 0x08;
	*((int16_t*)data.Data) = (int16_t)(enr_temr*100);
	*((int16_t*)data.Data+1) = (int16_t)(box_temp*100);
	*((int16_t*)data.Data+2) = (int16_t)(target*100);
	*((uint16_t*)data.Data+3) = ADC_Value;
	data.Data_End = 0x55;

	//最后发送
	SYS_Current_Data_Send(&data,(data.Data_Length+4));

	return 0;
}













